<?php
require_once("../include/main.php");
if(!isset($_SESSION['id'])){
	echo "error";
	die();
}
if(isset($_GET['op'])) {
	switch($_GET['op']) {
		case 'index':
			//echo $_SESSION['id'];
			$result = $db->query('SELECT book.id, room_id AS room, user_id, name AS user, start_time AS start, end_time AS end, content AS title, verify AS v FROM book, user WHERE book.user_id = user.id');
			foreach($result as &$r) {
				$r['start'] = date('Y-m-d\TH:i:s', (int)$r['start']);
				$r['end'] = date('Y-m-d\TH:i:s', (int)$r['end']);
				//if($r['user']!=$_SESSION['id']) $r['readOnly'] = 'true';
				if($r['user_id']!=$_SESSION['id']) $r['not'] = true;
				else $r['not'] = false;
				//$r['body'] = "事由：".$r['title']."<br />预约人：".$r['user']."<br />会议室：".$r['room'];
			}
			//print_r($result);
			echo json_encode($result);
			break;
		case 'create':
			if(isset($_POST)) {
				//print_r($_POST);
				$start = strtotime($_POST['start']);
				$end = strtotime($_POST['end']);
				$roomid = $_POST['room'];
				$title = $_POST['title'];
				$userid = $_SESSION['id'];
				$sql = "INSERT INTO book (room_id, user_id, start_time, end_time, content, verify) VALUES (".$roomid.",".$userid.",".$start.",".$end.",'".$title."',0)";
				//print $sql;
				$r = $db->execute($sql);
				if($r) echo "等待管理员审核！";
			}
			break;
		case 'update':
			if(isset($_POST)) {
				//print_r($_POST);
				if($_POST['uid']!=$_SESSION['id']) {
					echo "你没有修改此预约的权限";
				}else{
					$start = strtotime($_POST['start']);
					$end = strtotime($_POST['end']);
					$roomid = $_POST['room'];
					$title = $_POST['title'];
					$bid = $_POST['bid'];
					if(is_numeric($bid)) {
						$sql = "UPDATE book SET room_id=".$roomid.",start_time=".$start.",end_time=".$end.",content='".$title."' WHERE id=".$bid;
						//echo $sql;
						$r = $db->execute($sql);
						if($r) echo "预约修改成功！";
					}
				}
			}
			break;
		case 'delete':
			if(isset($_POST)) {
				//print_r($_POST);
				if($_POST['uid']!=$_SESSION['id']) {
					echo "你没有删除此预约的权限";
				}else{
					$bid = $_POST['bid'];
					if(is_numeric($bid)) {
						$sql = "DELETE FROM book WHERE id=".$bid;
						//print $sql;
						$r = $db->execute($sql);
						if($r) echo "预约删除成功！";
					}
				}
			}
			break;
	}
}